package cn.wolfcode.service.impl;

import cn.wolfcode.domain.User;
import cn.wolfcode.domain.UserInfo;
import cn.wolfcode.exception.BusinessException;
import cn.wolfcode.exception.CodeMsg;
import cn.wolfcode.mapper.UserMapper;
import cn.wolfcode.redis.RedisKey;
import cn.wolfcode.service.IUserInfoService;
import cn.wolfcode.service.IUserService;
import cn.wolfcode.util.MD5Util;
import cn.wolfcode.vo.LoginResponseVo;
import com.alibaba.fastjson.JSON;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * Created by wolfcode-lanxw
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IUserInfoService userInfoService;
    @Override
    public LoginResponseVo login(String phone, String password) {
        User user = getUser(phone);
        if(user==null || !user.getPassword().equals(MD5Util.encode(password,user.getSalt()))){
            throw new BusinessException(CodeMsg.INVALID_LOGIN_CREDENTIALS);
        }
        String token = createToken(user.getId());
        LoginResponseVo vo  = new LoginResponseVo();
        vo.setToken(token);
        UserInfo userInfo = userInfoService.getUserInfo(user.getId());
        vo.setInfo(userInfo);
        return vo;
    }
    @Override
    public User getUser(String phone) {
        String key = RedisKey.USER_STRING.getRealKey(phone);
        String objStr = redisTemplate.opsForValue().get(key);
        User user = null;
        if(StringUtil.isNullOrEmpty(objStr)){
            user = userMapper.getUserByPhone(phone);
            if(user!=null){
                redisTemplate.opsForValue().set(key, JSON.toJSONString(user),RedisKey.USER_STRING.getExpireTime(),RedisKey.USER_STRING.getUnit());
            }
        }else{
            user = JSON.parseObject(objStr, User.class);
        }
        return user;
    }

    private String createToken(Long userId){
        String token = UUID.randomUUID().toString().replace("-","");
        String key = RedisKey.USER_TOKEN_STRING.getRealKey(token);
        redisTemplate.opsForValue().set(key,userId.toString(),RedisKey.USER_TOKEN_STRING.getExpireTime(),RedisKey.USER_TOKEN_STRING.getUnit());
        return token;
    }
}
